<script setup lang="ts">
import { useAppStore } from "@/store/modules/app";
import { ref } from "vue";
import { onMounted } from "vue";
import { watch } from "vue";
import { computed } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { LoadingOutlined } from "@ant-design/icons-vue";
import { Input, Upload, UploadProps, Button, message } from "ant-design-vue";
import { store } from "@/store";
import metaidv2Utils from "@/utils/metaidv2Utils";
import { userStore } from "@/store/modules/walletUser";

const name = ref();
const loadName = ref(false);
const walletUser = userStore(store);
const userInfo: any = computed(() => walletUser.getUserInfoObj);

const fileList = ref<UploadProps["fileList"]>([]);
const imageUrl: any = ref();
const appStore = useAppStore();
const isMobile = ref(appStore.isMobile);

onMounted(() => {
  watch(
    () => walletUser.getUserInfoObj,
    (val) => {
      if (val.name && !loadName.value) {
        loadName.value = true;
        name.value = val.name;
      }
    }
  );
  if (walletUser.getUserInfoObj?.name && !loadName.value) {
    name.value = walletUser.getUserInfoObj.name;
    loadName.value = true;
  }
});

const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  fileList.value = [...(fileList.value || []), file];
  console.log("fileList", fileList.value);
  imageUrl.value = URL.createObjectURL(
    (fileList.value ? fileList.value[0] : null) as unknown as Blob
  );
  return false;
};

const uploadImage = async () => {
  const current: any = fileList.value ? fileList.value[0] : {};
  const compressed = await metaidv2Utils.compressImage(current.originFileObj);
  const fileResult = await metaidv2Utils.fileToAttachment(
    current.type === "image/gif" ? current.originFileObj : compressed
  );
  let opReturnFieldList = [
    Buffer.from("metaid"),
    Buffer.from("create"),
    Buffer.from("/info/avatar"),
    Buffer.from("0"),
    Buffer.from("1.0.0"),
    Buffer.from(`${fileResult.fileType};binary`),
    Buffer.from(Buffer.from(fileResult.data, "hex")),
  ];

  const res = await window.$walletUtils.createPin(opReturnFieldList);
  if (res) {
    userInfo.value.avatar = "/content/" + res + "i0";
    walletUser.changeUserInfoObj(userInfo.value);
  }
};

async function submitSettingNickname(nickname) {
  let opReturnFieldList = [
    Buffer.from("metaid"),
    Buffer.from("create"),
    Buffer.from("/info/name"),
    Buffer.from("0"),
    Buffer.from("1.0.0"),
    Buffer.from(`text/plain;utf8`),
    Buffer.from(nickname),
  ];
  const res = await window.$walletUtils.createPin(opReturnFieldList);
  if (res) {
    userInfo.value.name = nickname;
    await walletUser.changeUserInfoObj(userInfo.value);
  }
}

async function submit() {
  await submitSettingNickname(name.value);
  if (fileList.value && fileList.value.length > 0) {
    await uploadImage();
  }
  message.success("success");
  setTimeout(() => {
    // 刷新页面
    window.location.reload();
  }, 200);
}
</script>

<template>
  <div class="setting-wrap">
    <div v-if="!isMobile" class="content-left"></div>
    <div class="content-center">
      <div class="body">
        <div class="item">
          <div class="title">name</div>
          <div class="content">
            <Input v-model:value="name" type="text" />
          </div>
        </div>
        <div class="item">
          <div class="title">Avatar</div>
          <div class="content">
            <Upload
              v-model:file-list="fileList"
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleChange"
            >
              <img
                v-if="imageUrl"
                style="width: 100%"
                :src="imageUrl"
                alt="avatar"
              />
              <div v-else>
                <LoadingOutlined v-if="loading"></LoadingOutlined>
                <PlusOutlined v-else></PlusOutlined>
                <div class="ant-upload-text">Upload</div>
              </div>
            </Upload>
          </div>
        </div>
        <div class="footer">
          <Button type="primary" size="large" @click="submit">Save</Button>
        </div>
      </div>
    </div>
    <div v-if="!isMobile" class="content-right"></div>
  </div>
</template>

<style lang="less" scoped>
.setting-wrap {
  display: flex;
  height: 100%;
  overflow: auto;
  background: #f1f1f1;

  .content-right {
    flex: 1;
  }

  .content-center {
    flex: 1.5;
    align-content: flex-start;

    .body {
      padding: 30px;
      margin-top: 20px;
      background: #fff;
      border-radius: 10px;

      .item {
        margin-bottom: 20px;
      }

      .footer {
        display: flex;
        justify-content: center;
      }
    }
  }

  .content-left {
    flex: 1;
  }
}
</style>